package com.wentao.mall.service.impl;

import com.wentao.mall.commons.Constant;
import com.wentao.mall.exception.MallException;
import com.wentao.mall.exception.MallExceptionEnum;
import com.wentao.mall.mapper.UserMapper;
import com.wentao.mall.model.po.User;
import com.wentao.mall.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    public void register(String userName,String password) {
       User user= userMapper.selectByUserName(userName);
       if (user==null){
           User insertUser=new User();
           String s = DigestUtils.md5Hex(password+Constant.salt);
           insertUser.setUsername(userName);
           insertUser.setPassword(s);
           int count = userMapper.insertSelective(insertUser);
           if (count==0){
               throw new MallException(MallExceptionEnum.USER_INSERT_FAILED);
           }
       }
       else
           throw new MallException(MallExceptionEnum.NAME_ALREADY_EXISTS);
    }

    @Override
    public User login(String userName, String password) {
        User user=userMapper.selectByNameAndPwd(userName,DigestUtils.md5Hex(password+Constant.salt));
        if (user==null){
            throw new MallException(MallExceptionEnum.WRONG_USER_PWD);
        }
        return user;
    }

    @Override
    public void personalSignature(String signature,User user) {
        int count = userMapper.updateByPrimaryKeySelective(user);
        if (count==0){
            throw new MallException(MallExceptionEnum.UPDATE_FAINED);
        }
    }
}
